package com.huluobo.jetpackkotlindemo.livedata_viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel

/**
 * Created by lc on 2022/12/2.
 * LiveData总结:
 * 1.LiveData是一个可以被观测的对象,一般通过Observer来进行观测,当他发生改变的同时,会触发onChange回调
 * 2.map方法是为了转换某一个属性可以被观测到,同时修改对应LiveData中的对象
 * 3.switchMap方法是为了通过观测一个对象来找到对应的另一个LiveData的方法
 * 4.LiveData,ViewModel,和LifeCycle是联用
 */
class StudentViewModel : ViewModel() {
    private var studentLiveData = MutableLiveData<Student>()
    private var studentIdLiveData = MutableLiveData<String>()

    val _student: LiveData<Int>
        //修改观测对象,因为一个学生类中id和名字是不会发生变化的,发生变化的只会是分数,所以只需要观测分数就可以
        get() = Transformations.map(studentLiveData) {
            it.score
        }

    /**
     * 设置学生信息的方法
     */
    fun setStudentMessage(student: Student) {
        studentLiveData.value = student
    }

    /**
     * 获取分数
     */

    fun getScore(id: String): LiveData<Int> {
        return StudentResp().getStudentScore(id)
    }

    fun setStudentId(studentId: String) {
        studentIdLiveData.value = studentId
    }

    private fun getStudentId(studentId: String): LiveData<Int> {
        return StudentResp().getStudentScore(studentId)
    }

    var newScore: LiveData<Int> = Transformations.switchMap(studentIdLiveData, ::getStudentId)
}